package com.xhsj.user.hr.process.hrChangeSalary.service;

import com.xhsj.user.hr.process.dto.hrChangeSalary.MyChangeSalaryApplyListDto;
import com.xhsj.user.hr.process.dto.hrChangeSalary.ReturnChangeSalaryApplyDto;
import com.xhsj.user.hr.process.dto.hrChangeSalary.RunChangeSalaryApplyListDto;
import com.xhsj.user.hr.process.dto.hrTransferJob.ReturnTransferJobApplyDto;
import com.xhsj.user.hr.process.dto.processDefinition.HandleAuditDto;
import com.xhsj.user.hr.process.hrBecomeRegular.service.TbHrApprovalBecomeRegularApplyService;
import com.xhsj.user.hr.process.hrChangeSalary.entity.TbHrApprovalChangeSalary;
import com.xhsj.user.hr.process.hrChangeSalary.mapper.TbHrApprovalChangeSalaryMapper;
import com.xhsj.user.hr.process.hrChangeSalary.query.*;
import com.xhsj.user.hr.process.hrChangeSalary.service.TbHrApprovalChangeSalaryService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.process.hrEntryProcess.service.TbHrApprovalEntryApplyService;
import com.xhsj.user.hr.process.hrLeaveProcess.mapper.TbHrApprovalLeaveApplyMapper;
import com.xhsj.user.hr.process.hrLeaveProcess.query.ApprovalHiTaskQuery;
import com.xhsj.user.hr.process.hrLeaveProcess.query.WorkFlowNodeQuery;
import com.xhsj.user.hr.process.hrTransferJob.entity.TbHrApprovalTransferJob;
import com.xhsj.user.hr.process.processDefinition.query.ProcessNodeQuery;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalHiTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalApprovalTaskService;
import com.xhsj.user.hr.process.processDefinition.service.TbGlobalWorkFlowNodeService;
import com.xhsj.user.hr.process.query.ApprovalQuery;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.entity.TbGlobalUser;
import com.xhsj.user.hr.system.mapper.TbGlobalRoleMapper;
import com.xhsj.user.hr.userInfo.entity.TbGlobalUserDetail;
import com.xhsj.user.hr.userInfo.entity.TbGlobalUserSalary;
import com.xhsj.user.hr.userInfo.service.TbGlobalUserDetailService;
import com.xhsj.user.hr.userInfo.service.TbGlobalUserSalaryService;
import com.xhsj.user.utils.MessageConstant;
import com.xhsj.user.utils.UserUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import lombok.extern.slf4j.Slf4j;
/**
 * <p>
 * hr流程_调薪申请 服务实现类
 * </p>
 *
 * @author liuqinghua
 * @since Sep 14, 2020 10:55:13 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbHrApprovalChangeSalary")
public class TbHrApprovalChangeSalaryService extends BaseService<TbHrApprovalChangeSalaryMapper, TbHrApprovalChangeSalary>{
    @Autowired
    private TbHrApprovalChangeSalaryMapper dao;

    // 角色信息表 Mapper 接口
    @Autowired
    private TbGlobalRoleMapper tbGlobalRoleMapper;

    // 流程-历史表 服务实现类
    @Autowired
    private TbGlobalApprovalHiTaskService tbGlobalApprovalHiTaskService;

    // 流程设计-流程节点 服务实现类
    @Autowired
    private TbGlobalWorkFlowNodeService tbGlobalWorkFlowNodeService;

    // 流程-任务审核表 服务实现类
    @Autowired
    private TbGlobalApprovalTaskService tbGlobalApprovalTaskService;

    // 用户_详细信息 服务实现类
    @Autowired
    private TbGlobalUserDetailService tbGlobalUserDetailService;

    // 用户_薪资情况 服务实现类
    @Autowired
    private TbGlobalUserSalaryService tbGlobalUserSalaryService;

    // hr流程-入职申请表 服务实现类
    @Autowired
    private TbHrApprovalEntryApplyService tbHrApprovalEntryApplyService;

    @Autowired
    private TbHrApprovalBecomeRegularApplyService tbHrApprovalBecomeRegularApplyService;

    @Autowired
    private TbHrApprovalLeaveApplyMapper tbHrApprovalLeaveApplyMapper;
	/**
	 * 保存
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalChangeSalary", allEntries=true)
    public boolean save(TbHrApprovalChangeSalary entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbHrApprovalChangeSalary getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbHrApprovalChangeSalary", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbHrApprovalChangeSalary> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbHrApprovalChangeSalary entity = JSON.parseObject(JSON.toJSONString(data), TbHrApprovalChangeSalary.class);
        Page<TbHrApprovalChangeSalary> page = new Page(currentPage,pageSize);
        QueryWrapper<TbHrApprovalChangeSalary> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author liuqinghua
	 * @date Sep 14, 2020 10:55:13 AM
	 */
    @Override
    //@Cacheable(value = "TbHrApprovalChangeSalary",sync = true)
    public List<TbHrApprovalChangeSalary> selectAll() {
        return super.selectAll();
    }


    /**
     * 我的调薪申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<MyChangeSalaryApplyListQuery> myChangeSalaryApplyList(MyChangeSalaryApplyListDto data) {
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        Page<MyChangeSalaryApplyListDto> page = new Page<>(data.getPage(),data.getSize());
        return dao.myChangeSalaryApplyList(page,userId,data);
    }

    /**
     * 待审核调薪申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<RunChangeSalaryApplyListQuery> runChangeSalaryApplyList(RunChangeSalaryApplyListDto data) {
        Page<RunChangeSalaryApplyListQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        // 获取用户角色id
        List<Long> roleList = tbGlobalRoleMapper.getRoleListByUserId(userId);
        return dao.runChangeSalaryApplyList(page,userId,roleList,data);
    }

    /**
     * 已审核调薪申请列表
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public IPage<CompletedChangeSalaryApplyQuery> completedChangeSalaryApplyList(RunChangeSalaryApplyListDto data) {
        Page<CompletedChangeSalaryApplyQuery> page = new Page<>(data.getPage(),data.getSize());
        LoginUser loginAppUser = UserUtils.getLoginAppUser();
        Long userId = loginAppUser.getUserId();
        return dao.completedChangeSalaryApplyList(page,userId,data);
    }

    /**
     * 我的调薪申请详细信息
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public MyChangeSalaryApplyDetailedListQuery myChangeSalaryApplyDetailedList(Long dataId) {
        MyChangeSalaryApplyDetailedListQuery myChangeSalaryApplyDetailedListQuery= new MyChangeSalaryApplyDetailedListQuery();
        // 调薪申请基本信息
        ChangeSalaryApplyBaseDetailedQuery apply = dao.changeSalaryApplyBaseDetailedList(dataId);
        if (apply != null) {
            Long businessId = apply.getBusinessId();
            myChangeSalaryApplyDetailedListQuery.setApply(apply);
            // 审批意见
        List<ApprovalHiTaskQuery> approvalHiTaskList = tbGlobalApprovalHiTaskService.getApprovalHiTaskList(dataId, businessId);
        myChangeSalaryApplyDetailedListQuery.setCommentList(approvalHiTaskList);

        // 流程节点
        List<WorkFlowNodeQuery> workFlowNodeQueries = tbGlobalWorkFlowNodeService.nodeList(businessId);
        myChangeSalaryApplyDetailedListQuery.setNodeList(workFlowNodeQueries);
        }
        return myChangeSalaryApplyDetailedListQuery;
    }

    /**
     * hr流程-调薪申请开始
     * @author liuqinghua
     * @date Sep 7, 2020 10:42:13 AM
     */
    public ApprovalQuery startChangeSalaryApply(TbHrApprovalChangeSalary data) throws Exception {
        // 保存调薪
        if (!super.save(data)) {
            throw new Exception("保存调薪信息异常");
        }
        // 执行流程
        return this.startChangeSalaryApplyRun(data);
    }

    /**
     * 执行开始调薪流程启动
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery startChangeSalaryApplyRun(TbHrApprovalChangeSalary apply) throws Exception {
        HandleAuditDto handleAuditDto = new HandleAuditDto();
        handleAuditDto.setDataId(apply.getId());
        handleAuditDto.setProposerId(apply.getCreateBy());
        handleAuditDto.setCreateBy(apply.getCreateBy());
        handleAuditDto.setApplyType(9);
        // 执行流程
        ProcessNodeQuery processNodeQuery = tbGlobalApprovalTaskService.startHandleAudit(handleAuditDto,apply.getDepartmentId());
        // 修改调薪申请表节点名称和节点id
       return this.updateHrApprovalChangeSalaryApply(handleAuditDto,processNodeQuery);
    }

    // 修改节点id和节点名称调薪申请
    public ApprovalQuery updateHrApprovalChangeSalaryApply(HandleAuditDto data,ProcessNodeQuery processNodeQuery) throws Exception {
        //修改调薪申请表节点名称和节点id
        TbHrApprovalChangeSalary tbHrApprovalChangeSalary = new TbHrApprovalChangeSalary();
        tbHrApprovalChangeSalary.setId(data.getDataId());
        tbHrApprovalChangeSalary.setNodeName(processNodeQuery.getNodeName());
        tbHrApprovalChangeSalary.setNodeId(processNodeQuery.getNodeId());
        tbHrApprovalChangeSalary.setBusinessId(data.getBusinessId());
        tbHrApprovalChangeSalary.setDelFlag(processNodeQuery.getDelFlag());
        if (!this.save(tbHrApprovalChangeSalary)) {
            throw new Exception("修改调薪申请节点名称信息异常");
        }
        String fullName = tbHrApprovalLeaveApplyMapper.getFullNameByDataId(data.getDataId(),"tb_hr_approval_change_salary");
        // 消息参数
        return tbHrApprovalBecomeRegularApplyService.setApprovalQuery(data.getDataId(),
                4,
                MessageConstant.MSG_8,
                processNodeQuery,
                fullName);
    }

    /**
     * 调薪流程审批
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalChangeSalaryApply(HandleAuditDto data) throws Exception {
        // 执行流程
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);
        // 修改产品申请表节点名称和节点id
        ApprovalQuery approvalQuery = updateHrApprovalChangeSalaryApply(data,processNodeVo);

        if ("完结".equals(processNodeVo.getNodeName()) ) {
            // 当前时间
            Date day = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String format = df.format(day);
            long time = df.parse(format).getTime();
            // 获取调整后得薪资
            TbHrApprovalChangeSalary tbHrApprovalChangeSalary = dao.selectById(data.getDataId());
            if (time == tbHrApprovalChangeSalary.getEffectiveDate().getTime()) {
            Long userId = tbHrApprovalChangeSalary.getUserId();
            BigDecimal newSalary = tbHrApprovalChangeSalary.getNewSalary();
            // 修改薪资
            TbGlobalUserDetail tbGlobalUserDetail = new TbGlobalUserDetail();
            tbGlobalUserDetail.setSalary(newSalary);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id",userId);
            if (!tbGlobalUserDetailService.update(tbGlobalUserDetail,queryWrapper)) {
                throw new Exception("修改薪资信息异常");
            }
            // 获取之前得工资信息
            QueryWrapper<TbGlobalUserSalary> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id",userId);
            queryWrapper1.eq("stauts",0);
            TbGlobalUserSalary one = tbGlobalUserSalaryService.getOne(queryWrapper1);
            // 修改工资表里得状态
            TbGlobalUserSalary tbGlobalUserSalary = new TbGlobalUserSalary();
            tbGlobalUserSalary.setId(one.getId());
            tbGlobalUserSalary.setStauts(1);
            tbGlobalUserSalaryService.updateById(tbGlobalUserSalary);
            Integer salaryType = one.getSalaryType();
            tbHrApprovalEntryApplyService.saveSalary(userId,newSalary,salaryType);
        }
        }
        return approvalQuery;
    }

    /**
     * 调新定时器 定期生效
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public void approvalChangeSalaryEffective() throws Exception {
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String format = df.format(day);
        // 获取今天将生效的调新
        QueryWrapper<TbHrApprovalChangeSalary> queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("effective_date",format);
        queryWrapper2.eq("node_name","完结");
        List<TbHrApprovalChangeSalary> tbHrApprovalChangeSalaryJobs = dao.selectList(queryWrapper2);
        for (TbHrApprovalChangeSalary tbHrApprovalChangeSalary : tbHrApprovalChangeSalaryJobs) {
            Long userId = tbHrApprovalChangeSalary.getUserId();
            BigDecimal newSalary = tbHrApprovalChangeSalary.getNewSalary();
            // 修改薪资
            TbGlobalUserDetail tbGlobalUserDetail = new TbGlobalUserDetail();
            tbGlobalUserDetail.setSalary(newSalary);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id",userId);
            if (!tbGlobalUserDetailService.update(tbGlobalUserDetail,queryWrapper)) {
                throw new Exception("修改薪资信息异常");
            }
            // 获取之前得工资信息
            QueryWrapper<TbGlobalUserSalary> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id",userId);
            queryWrapper1.eq("stauts",0);
            TbGlobalUserSalary one = tbGlobalUserSalaryService.getOne(queryWrapper1);
            // 修改工资表里得状态
            TbGlobalUserSalary tbGlobalUserSalary = new TbGlobalUserSalary();
            tbGlobalUserSalary.setId(one.getId());
            tbGlobalUserSalary.setStauts(1);
            tbGlobalUserSalaryService.updateById(tbGlobalUserSalary);
            Integer salaryType = one.getSalaryType();
            tbHrApprovalEntryApplyService.saveSalary(userId,newSalary,salaryType);
        }

    }

    /**
     * 调薪申请重新提交
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery returnChangeSalaryApply(ReturnChangeSalaryApplyDto data) throws Exception {
        // 修改申请数据
        TbHrApprovalChangeSalary apply = data.getApply();
        if (!super.save(apply)) {
            throw new Exception("修改申请数据异常");
        }
        // 执行流程
        HandleAuditDto handleAudit = data.getHandleAuditDto();
      return this.approvalChangeSalaryApply(handleAudit);
    }

    /**
     * 调薪申请删除
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public boolean deleteChangeSalaryApply(Long dataId) throws Exception {
        int i = dao.deleteChangeSalaryApply(dataId);
        if (i == 0) {
            throw new Exception("调薪申请删除异常");
        }
        return true;
    }

    /**
     * 调薪流程作废
     * @author liuqinghua
     * @date Sep 1, 2020 10:07:11 AM
     */
    public ApprovalQuery approvalChangeSalaryToVoidApply(HandleAuditDto data) throws Exception {
        // 执行流程
        data.setNodeId(-11L);
        ProcessNodeQuery processNodeVo = tbGlobalApprovalTaskService.handleAudit(data);
        // 修改产品申请表节点名称和节点id
       return updateHrApprovalChangeSalaryApply(data,processNodeVo);
    }
}
